import com.alibaba.fastjson.JSONObject;
import com.binguo.api.response.api.BaseChargeResp;
import com.binguo.api.response.api.BaseUserInfo;
import com.binguo.api.service.ApiOrderService;
import com.binguo.api.service.api.ShopApiInterface;
import com.binguo.common.enums.PayStatus;
import com.binguo.common.enums.PayType;
import com.binguo.common.exception.ServiceException;
import com.binguo.model.api.dto.OrderDTO;
import com.binguo.model.api.vo.OrderVO;
import com.binguo.model.model.Customer;
import com.binguo.model.model.PayCard;
import com.binguo.model.repository.CustomerRepository;
import com.binguo.service.CustomerService;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.converter.StringHttpMessageConverter
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource
import java.nio.charset.Charset

import static com.binguo.common.exception.ErrorCode.CUSTOMER_NOT_EXIST;

/**
 * @author yuritian
 * @Title: zhaoShangService
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2020/6/22 15:22
 */
public class ZhaoShangService implements ShopApiInterface {

    @Resource
    CustomerService customerService;

    @Resource
    ApiOrderService apiOrderService;

    @Resource
    CustomerRepository customerRepository;

    @Override
    public BaseChargeResp payPreHandler(OrderDTO orderDTO) {
        if (orderDTO.getPayType().equals(PayType.CARDPAY)){

            return cardPay(orderDTO);
        }else if (orderDTO.getPayType().equals(PayType.FACEPAY)){

            return facePay(orderDTO);
        }else {
            throw new ServiceException("不支持支付方式");
        }
    }

    @Override
    public BaseChargeResp payPostHandler(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseUserInfo getUserInfo(String cardNo) {
        return null;
    }

    @Override
    public BaseChargeResp getProductList() {
        return null;
    }

    @Override
    public BaseChargeResp cardPay(OrderDTO orderDTO) {
        BaseChargeResp<OrderVO> resp = new BaseChargeResp<>();

        String phone = getPhone(orderDTO.getCardNo());

        if (!StringUtils.hasText(phone)){
            throw new ServiceException("卡查询失败");
        }

        Customer customer = customerService.getCustomerByPhone(phone);
        if(customer == null){
            throw new ServiceException("不存在会员");
        }
        Optional<PayCard> cardOptional = customerService.findPayCard(orderDTO.getShopId(), customer.getId());
        if (!cardOptional.isPresent()) {
            throw new ServiceException(CUSTOMER_NOT_EXIST);
        }

        JSONObject result = zhaoShangPay(phone,orderDTO.getRealFee());

        Integer code = result.getInteger("code");

        if (code.equals(200)){
            OrderVO orderVO = apiOrderService._createOrder(orderDTO, PayStatus.SUCCESS);
            resp.setData(orderVO);
            resp.setCode(200);
            return resp;
        }else {
            throw new ServiceException("支付失败");
        }
    }

    @Override
    public BaseChargeResp wxPay(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseChargeResp aliPay(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseChargeResp facePay(OrderDTO orderDTO) {
        BaseChargeResp<OrderVO> resp = new BaseChargeResp<>();

        JSONObject result = zhaoShangPay(orderDTO.getCustomerPhone(),orderDTO.getRealFee());

        Integer code = result.getInteger("code");

        if (code.equals(200)){
            OrderVO orderVO = apiOrderService._createOrder(orderDTO, PayStatus.SUCCESS);
            resp.setData(orderVO);
            resp.setCode(200);
            return resp;
        }else {
            throw new ServiceException("支付失败");
        }
    }

    @Override
    public BaseChargeResp cashPay(OrderDTO orderDTO) {
        return null;
    }

    @Override
    public BaseChargeResp qrCodePay(OrderDTO orderDTO) {
        return null;
    }

    public JSONObject zhaoShangPay(String phone,Long realFee){

        JSONObject postParm = new JSONObject();
        postParm.put("phone",phone);
        postParm.put("amount",realFee);

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(postParm.toJSONString(), headers);
        //ResponseEntity<String> resp = restTemplate.postForEntity("http://115.236.162.166:8888/mcap/api/entra", entity, String.class);
        ResponseEntity<String> resp = restTemplate.postForEntity("http://192.168.1.16:8888/ytintermediateservice/pay", entity, String.class);
        String result = resp.getBody();
        System.out.println(result);
        JSONObject postResult = JSONObject.parseObject(result);
        return postResult;
    }


    public String getPhone(String cardNo){

        JSONObject postParm = new JSONObject();
        postParm.put("cardNo",cardNo);

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(postParm.toJSONString(), headers);
        //ResponseEntity<String> resp = restTemplate.postForEntity("http://115.236.162.166:8888/mcap/api/entra", entity, String.class);
        ResponseEntity<String> resp = restTemplate.postForEntity("http://192.168.1.16:8888/ytintermediateservice/getAccNumByCardNo", entity, String.class);
        String result = resp.getBody();
        System.out.println(result);
        JSONObject postResult = JSONObject.parseObject(result);
        Integer code = postResult.getInteger("code");
        if (code.equals(200)){
            String data = postResult.getString("data");
            return data;
        }else {
            return null;
        }
    }
}
